let CRC = require("../../../utils/CRC")
let app = getApp()
const plugin = requirePlugin('quecPlugin')
Page({
  handleGetBack: function() {
    wx.reLaunch({
      url: '/pages/home/home',
    }) 
  },
  
  handleSetupParameter: function () {
    console.log(this.data.getOptions);
    wx.navigateTo({
      url: `/pages/device_setup/index?item=${JSON.stringify(this.data.curDevice)}`,
    })
    //item=${JSON.stringify(item)}
  },
  handleUiSet: function(){
    console.log(this.data.getOptions);
    wx.navigateTo({
      url:'/pages/ui_set/ui_set'
    })
},


  data: {
    curDevice: {},
    pk: '',
    dk: '',
    textDetail: {},
    column3Widht: 0,
    //页头信息
    vfdStatusStyel:"",
    headerStatutsStr:"",
    headerRingIconImage:"",
    headerRingContentStr:"",
    headerRingRemarkStr:"",
    headerContentSpeedStr:"",
    headerContentVoltageStr:"",
    offlineImage:"../../../images/offline_icon.png",
    poweredImage:"../../../images/frequency_icon.png",
    unpoweredImage:"../../../images/off_detail_icon.png",
    warningImage:"../../../images/warning_icon.png",
    loadingImage:"../../../images/loading_icon.png",
    backtrackIconImage:"../../../images/backtrack_icon.png",
    speedImage:"../../../images/speed_icon.png",
    voltageIconImage:"../../../images/voltage_icon.png",
    forwardImage:"../../../images/forward_icon.png",
    reverseIconImage:"../../../images/reverse_icon.png",
    forwardJogImage:"../../../images/forward_jog_icon.png",
    reverseJogIconImage:"../../../images/reverse_jog_icon.png",
    vfdSwitchIconImage:"../../../images/vfd_switch.png",
    ringStatus:"",
    focusOperateStatus:"OPERATE01",

    faultNum:"0",//故障码
    busVoltage:"0",//母线电压
    setupFrequency:"0.0",//设定频率    
    getFrequency:"请输入频率",//运行频率
    outputPower:"0",//输出功率
    outputVoltage:"0",//输出电压
    outputAmps:"0",//输出电流
    outputTorque:"0",//输出转矩
    operateStatus:"3",//运行状态
    outputSpeed:"0",//运行转速
    operateFrequency:"0.0",//运行频率
    frequencyRange:"50",
    setupFrequencyEnabled: false,
    operateStatusStr:{"0":"数据读取中...","1":"正转运行", "2":"反转", "3":"停机"},
    faultStr:{
        "0":"",
        "1":"逆变模块保护",
        "2":"加速过电流",
        "3":"减速过电流",
        "4":"恒速过电流",
        "5":"加速过电压",
        "6":"减速过电压",
        "7":"恒速过电压",
        "8":"控制电源故障",
        "9":"欠压保护",
        "10":"变频器过载",
        "11":"电机过载",
        "12":"输入缺相",
        "13":"输出缺相",
        "14":"模块过热",
        "15":"外部设备故障",
        "16":"通讯故障",
        "17":"接触器故障",
        "18":"电流检测故障",
        "19":"电机调谐故障",
        "21":"EEPROM读写故障",
        "22":"变频器硬件故障",
        "23":"对地短路故障",
        "26":"累计运行时间到达",
        "29":"累计上电时间到达",
        "40":"逐波限流故障",
        "41":"运行时切换电机故障",
        "42":"速度偏差过大故障",
        "52":"缺水报警",
        "53":"超压报警",
        "64":"通讯故障",
      },
      getOptions:'',
      destinationStationAddress:'01',
      functionCode:{
        "ReadHoldingRegister":"03",
        "PresetSingleRegister":"06"
      },
      modBusIdtoAdd:{
        1:"0002",
        2:"0001"
      },
      modbusAddtoName:{
        "0001":"setupFrequency",
        "0002":"controlCommand",
        "F009":"frequencyRange"
      },
      controlCommand:"",//控制命令
      intervalId:"",
      isAuthorized: false,
      writePermission: false,
      errCode:999,
      showHzorErr:false,
      nowStatus:false,

      motorPower: "0" //变频器功率
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    console.log("device_detail已加载");
    let self = this
    if (options.item) {
      let dItem = JSON.parse(decodeURIComponent(options.item))
      console.log(this.data.getOptions)
      // console.log("dItem:"+dItem.toStr)
      const systemInfo = wx.getSystemInfoSync();
      const screenWidth = systemInfo.screenWidth;
      const screenHeight = systemInfo.screenHeight;
      const column3Widht = (screenWidth - 20) / 3;
      const column3BoxSize = column3Widht - 20;
      //设置初始信息
      if(dItem.onlineStatus === 0){
        self.setData({
          vfdStatusStyel:"offline",
          headerRingIconImage: self.data.offlineImage,
          headerRingContentStr:"设备离线",
        });
      }else{
        self.setData({
          // vfdStatusStyel:"online",
          // headerRingContentStr:"数据加载",
          // headerRingIconImage: self.data.loadingImage,
          // headerRingRemarkStr:"11",
          vfdStatusStyel:"unpowered",
          headerStatutsStr:"停机",
          ringStatus:"",
          headerRingIconImage: this.data.unpoweredImage,
        });
      }
      self.setData({
        pk: dItem.productKey,
        dk: dItem.deviceKey,
        curDevice: dItem,
        screenWidth: screenWidth,
        screenHeight: screenHeight,
      })
      // console.log("屏幕尺寸：宽度 -> " + this.data.screenWidth + " , 高度 -> " + this.data.screenHeight)
      if (!app.globalData.isMsgCbExecuted) {
        app.globalData.mySocket = plugin.webSocket
        app.globalData.mySocket.connectSocket()    
        app.globalData.isMsgCbExecuted = true
      } 
      this.msgCb()
      this.verifyPwd()
    }
  },

  verifyPwd(){
    let self = this
    let writeCorrectPassword = app.globalData.writePassword
    let readCorrectPassword = app.globalData.readPassword
    let isOK = false
    try {
      let value = wx.getStorageSync('Pwd');
      if (value) {
        // 获取成功，value 即为对应的数据值
        // console.log(value);
        if(value === writeCorrectPassword){
          app.globalData.isAuthorized = true
          app.globalData.writePermission = true
          self.setData({
            isAuthorized:app.globalData.isAuthorized,
            writePermission:app.globalData.writePermission
          })    
          isOK = true
        }else if(value === readCorrectPassword){
          app.globalData.isAuthorized = true
          app.globalData.writePermission = false 
          self.setData({
            isAuthorized:app.globalData.isAuthorized,
            writePermission:app.globalData.writePermission
          })    
          isOK = true
        }
      }
    } catch (err) {
      // 获取失败，可能是因为该 key 不存在或读取错误
      console.error(err);
    }
    // console.log(isOK);
    if(!isOK){
      wx.showModal({
        title: '请输入权限密码',
        content: '',
        editable: true,
        success (res) {
          if (res.confirm) {  
            if (res.content === readCorrectPassword) {
              try {
                wx.setStorageSync('Pwd', readCorrectPassword);
                app.globalData.isAuthorized = true
                app.globalData.writePermission = false
                self.setData({
                  isAuthorized:app.globalData.isAuthorized,
                  writePermission:app.globalData.writePermission
                })    
                // 设置成功
              } catch (err) {
                // 设置失败
                console.error(err);
              }
              wx.showToast({
                title: '密码正确(只读)',
                icon: 'none',
                duration: 1000
              })

            } else if (res.content === writeCorrectPassword){
              try {
                wx.setStorageSync('Pwd', writeCorrectPassword);
                app.globalData.isAuthorized = true
                app.globalData.writePermission = true
                self.setData({
                  isAuthorized:app.globalData.isAuthorized,
                  writePermission:app.globalData.writePermission
                })    
                // 设置成功
              } catch (err) {
                // 设置失败
                console.error(err);
              }
              wx.showToast({
                title: '密码正确(允许读写)',
                icon: 'none',
                duration: 1000
              })
              // app.globalData.writePermission = true
            }else {
              // 密码错误，弹出提示框
              wx.showToast({
                title: '密码错误',
                icon: 'none',
                duration: 2000
              })
              setTimeout(function() {
                wx.reLaunch({
                  url: '/pages/home/home',
                }) 
              }, 2000);
            }
          } else if (res.cancel) {
            wx.reLaunch({
              url: '/pages/home/home',
            }) 
          }
        }
      }) 
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady () {
    this.sendMaxF()
    this.sendPower()
    this.send06()
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow () {
    this.sendMaxF()
    this.sendPower()
    this.send06()
    if(this.data.nowStatus == true){
      clearInterval(this.data.intervalId)
      this.data.intervalId = setInterval(this.send06,1000);
    }else{
      clearInterval(this.data.intervalId)
      this.data.intervalId = setInterval(this.send06,5000);
    }
  },
  editpage (e) {
    let item = e.detail
    const { pk, dk } = this.data
    switch (item.dataType) {
      case 'TEXT':
        wx.navigateTo({
          url: `./device_tsl_text/index?item=${JSON.stringify(item)}`
        })
        break
      case 'ARRAY':
        wx.navigateTo({
          url: `./device_tsl_array/index?item=${encodeURIComponent(JSON.stringify(item))}`
        })
        break
      case 'STRUCT':
        wx.navigateTo({
          url: `./device_tsl_struct/index?item=${JSON.stringify(item)}&pk=${pk}&dk=${dk}`
        })
        break
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () {
    clearInterval(this.data.intervalId)
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () {
    clearInterval(this.data.intervalId);
    app.globalData.mySocket.closeSocket()
    app.globalData.isMsgCbExecuted = false
    // app.globalData.writePermission = false
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () {
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () {
  },
  msgCb () {
    let self = this
    let subscribeDeviceKey = self.data.dk
    let subscribeProductKey = self.data.pk
    plugin.webSocket.msgCallback((res) => {
      if (res) {
        let parm = JSON.parse(res)
        if (parm.cmd === 'login_resp') {//登录
          // 登录回调
          if (parm.data.code === 1) {
            console.log('WebSocket 登录成功')
            // 登录完成后，进行设备订阅
            if (subscribeDeviceKey && subscribeProductKey) {
              let data = {
                pk: subscribeProductKey,
                dk: subscribeDeviceKey
              }
              plugin.webSocket.subscribeDevice(data)
            }
          } else {
            console.log('WebSocket  登录失败')
          }
        } else if (parm.cmd === 'subscribe_resp') {//订阅响应
          // 订阅响应回调
          console.log('WebSocket 订阅响应成功')
          
          if (parm.data && parm.data.length > 0) {
            if (parm.data[0].code === '4011') {
              wx.showToast('设备未绑定')
            }
          }
        } else if (parm.cmd === 'unsubscribe_resp') {//取消订阅
          // 取消订阅响应回调
          console.log('WebSocket  取消 订阅 成功')
          //清除订阅信息
          subscribeDeviceKey = ''
          subscribeProductKey = ''
        } else if (parm.cmd === 'send_ack') {//发送指令应答
          // 发送指令响应
          console.log('WebSocket  发送指令响应 应答', parm.data)
          if (parm.data.status == 'succ') {
            
            // wx.showToast('发送成功', 'success')
          } else {
            setTimeout(() => {
              wx.showToast('发送失败', 'error')
            }, 300)
          }
        } else if (parm.cmd === 'message') {
          //更新广播
          if (parm.data.type === undefined) {
            try {
              parm.data = JSON.parse(parm.data)
            } catch (e) {
              console.log(e)
            }
          }
          if (parm.data.type === 'MATTR') {//设备上报属性信息
            let reportData = parm.data.data.kv;
            this.getData(reportData)
            console.log(reportData); 
          } else if (parm.data.type === 'ENDUSER' && parm.data.subtype === 'USER-BIND') {
            wx.showToast('设备已失效')
          }
        } else if (parm.cmd === 'error') { //错误信息
          console.log('WebSocket   错误信息' + parm.data.msg)
        }
      }
    })
  },
  send (id,value) {
    if(!app.globalData.writePermission && (id != 1 && (value != 1 || value != 1 || value != 6)) && id != 2 ){
      wx.showToast({
        title: '您没有修改权限',
        icon: 'none',
        duration: 2000
      })
      return
    }
    let self = this
    let pk = self.data.pk
    let dk = self.data.dk
    let type = 'WRITE-ATTR'
    let str = self.data.destinationStationAddress + self.data.functionCode["PresetSingleRegister"] + self.data.modBusIdtoAdd[id]
    let mainCode = CRC.zeroPad(parseInt(value).toString(16),4)
    // console.log("mainCode:"+mainCode);
    let modbusCode = str + mainCode + CRC.ToModbusCRC16(str + mainCode)
    console.log("请求modbusCode:"+modbusCode);
    let sendData = [{
      id: 1,
      value: modbusCode.toUpperCase(),
      type: "RAW"
    }]
    plugin.webSocket.sendCmd({ pk, dk, type, sendData })
  },

  /*
  * 读取最大U0组前10个参数
  */
  send06(){
    // await this.msgCb()
    let self = this
    let pk = self.data.pk
    let dk = self.data.dk
    let type = 'WRITE-ATTR'
    let sendData = [{
      id: 1,
      value: "01031000000AC10D",
      type: "RAW"
    }]
    plugin.webSocket.sendCmd({ pk, dk, type, sendData })
    console.log("send06已执行");
  },

  /*
  * 读取最大频率
  */
  sendMaxF(){ 
    // await this.msgCb()
    let self = this
    let pk = self.data.pk
    let dk = self.data.dk
    let type = 'WRITE-ATTR'
    let sendData = [{
      id: 1,
      value: "0103F00900016708",
      type: "RAW"
    }]
    plugin.webSocket.sendCmd({ pk, dk, type, sendData })
    console.log("sendMaxF执行");
  },
 
  /*
  * 读取电机功率
  */
  sendPower(){
    // await this.msgCb()
    let self = this
    let pk = self.data.pk
    let dk = self.data.dk
    let type = 'WRITE-ATTR'
    let sendData = [{
      id: 1,
      value: "0103F8000002F56B",
      type: "RAW"
    }]
    plugin.webSocket.sendCmd({ pk, dk, type, sendData })
    console.log("sendPower执行");
  },

  frequencyInput: function(event) {
    let num = event.detail.value
    console.log(num);
    const reg = /^\d*\.?\d{0,1}$/;
    // let reg = /^(0|[1-9]\d*)(\.\d)?$/;
    if (reg.test(num) && parseFloat(num)>=0 && parseFloat(num)<=this.data.frequencyRange) {
      this.setData({
        setupFrequencyEnabled: true,
        getFrequency: parseFloat(num).toFixed(1),
      });
    }else{
      this.setData({
        setupFrequencyEnabled: false,
      });
      const keyCode = event.detail.keyCode || event.detail.charCode; // 兼容不同浏览器的keyCode获取方式
      console.log(keyCode);
      if(keyCode == 8){
        return;
      }
      wx.showToast({
        title: '输入格式错误，频率范围0~'+this.data.frequencyRange, // 提示的内容
        icon: 'none', // 提示的图标，支持"success"、"loading"等，默认为
        duration: 3000, // 提示的持续时间，单位毫秒，默认为1500
      })
    }
      
    
  },
  setupFrequency: function(){
    let fr = (this.data.getFrequency * 10000)/ this.data.frequencyRange
    this.send(2, fr)
    console.log("setupFrequency函数-fr:"+fr);
  },

  motorPower: function(){
    let fr = this.data.motorPower
    this.send(2, fr)
    console.log("变频器功率 motorPower:"+fr);
  },

  operateModel: function (event){
    const str = event.currentTarget.dataset.model;
    this.setData({
      focusOperateStatus: str,
    });
    if(this.data.vfdStatusStyel === "powered"){ 
      this.send(1, str.charAt(str.length - 1))
    }
  },
  
  switchOn: function (){
    const str = this.data.focusOperateStatus;
    this.send(1, str.charAt(str.length - 1))
    this.send06()
  },
  freeStop: function (){
    this.send(1, 6)
  },
  decelerationStop: function (){
    this.send(1, 6)
  },
  resetVfd: function(){
    this.send(1, 7)
  },
  getDataProcessingWrite: function(str){
      let add = str.slice(4,8)
      let valDec = parseInt(str.slice(8,12),16)
      let name = this.data.modbusAddtoName[add]
      if(name in this.data){
        if(name === "setupFrequency"){       
          let val = valDec/10000 * this.data.frequencyRange
          console.log("val:"+val);
          console.log("得到的setupFrequency:"+parseInt(val));
          this.setData({
            [name]:parseFloat(val).toFixed(1)
          })
        }
        if(name === "frequencyRange"){
          this.setData({
            [name]:parseInt(valDec)
          })
        }
        // if(name === "controlCommand" ){
        //   if(valDec == 5 || valDec == 6){
        //     this.setData({
        //       vfdStatusStyel:"unpowered",
        //       headerStatutsStr:"停机",
        //       ringStatus:"",
        //       headerRingIconImage: this.data.unpoweredImage,
        //     });
        //   }
        // }
       
      }else{

      }
  },
  getDataProcessingRead: function(str){
    //console.log("得到pageID："+app.globalData.pageID);
    console.log("得到str->length："+str.length);
    if(str.length < 40){
      if(app.globalData.pageID == "2"){//电机相关参数读取
        app.globalData.readParameterVal = parseInt(str.slice(6,10),16)
        console.log("得到电机参数："+app.globalData._readParameterVal);
      }else{
          //因为前面代码结构有问题, 没办法区分读到的modbus回传是那条指令的回传
          //这里判断电机功率是通过读电机功率F800和F801连着的两个指令, 通过指令的不同长度判断的
          if (str.length == 18) { 
            this.setData({
              motorPower:(parseInt(str.slice(6,10), 16)/1)
            })
            console.log("读取的motorPower:"+this.data.motorPower);
          } else {
            this.setData({
              frequencyRange:(parseInt(str.slice(6,10),16)/10)
            })
            console.log("读取的frequencyRange:"+this.data.frequencyRange);
          }
      }
      return
    }
    let codeArr = []
    let head = str.slice(0,6)
    str = str.slice(6,str.length)
    let len = 0
    while(str.length > 4){
      codeArr[len] = str.slice(0,4)
      str = str.slice(4,str.length)
      len = len + 1
    }

    this.setData({
      operateStatus:parseInt(codeArr[0],16)+"",
      faultNum:parseInt(codeArr[1],16),
      setupFrequency:(parseInt(codeArr[2],16)/10).toFixed(1),
      // headerRingContentStr:(parseInt(codeArr[3],16)/10).toFixed(1),
      operateFrequency:(parseInt(codeArr[3],16)/10).toFixed(1),
      headerContentSpeedStr:parseInt(codeArr[4],16)+"",
      outputSpeed:parseInt(codeArr[4],16)+"",
      outputVoltage:parseInt(codeArr[5],16)+"",
      //outputAmps:(parseInt(codeArr[6],16)/10).toFixed(1)+"",
      outputPower:(parseInt(codeArr[7],16)/10).toFixed(1)+"",
      busVoltage:parseInt(codeArr[8],16)+"",
      headerContentVoltageStr:(parseInt(codeArr[8],16)/1.414).toFixed(1),// 更改为输入电压
      outputTorque:parseInt(codeArr[9],16)+"",
    }) 
    //变换读取速度时间
    if(this.data.operateStatus == "3" && this.data.nowStatus == true){
      this.setData({
        'nowStatus':false
      })
      clearInterval(this.data.intervalId)
      this.data.intervalId = setInterval(this.send06,5000);
    }else if((this.data.operateStatus == "1" || this.data.operateStatus == "2") && this.data.nowStatus == false){
      this.setData({
        'nowStatus':true
      })
      clearInterval(this.data.intervalId)
      this.data.intervalId = setInterval(this.send06,1000);
    }
  
    //根据功率不同, 输出不同的电流数据(75及75kw以上机器的电流没有小数点)
    if (this.data.motorPower >= 750) {
      this.setData({
        outputAmps:(parseInt(codeArr[6],16)/1)+"",
      })
    } else {
      this.setData({
        outputAmps:(parseInt(codeArr[6],16)/10).toFixed(1)+"",
      })
    }

    if(this.data.errCode == this.data.faultNum){
      return
    }else if(this.data.faultNum !== 0){
      this.setData({
        errCode : this.data.faultNum,
        showHzorErr : true,
        vfdStatusStyel:"warning",
        headerStatutsStr:"故障",
        headerRingContentStr:"故障警报",
        headerRingIconImage: this.data.warningImage,
        headerRingRemarkStr: parseInt(this.data.faultNum),
      })
    }else if(this.data.operateStatus == "1"){
      this.setData({
        showHzorErr : false,
        headerStatutsStr:"正转运行",
        ringStatus:"forward",
        vfdStatusStyel:"powered",
        headerRingIconImage: this.data.poweredImage,
        headerRingRemarkStr:"Hz",
      });
    }else if(this.data.operateStatus == "2"){
      this.setData({
        showHzorErr : false,
        headerStatutsStr:"反转运行",
        ringStatus:"reverse",
        vfdStatusStyel:"powered",
        headerRingIconImage: this.data.poweredImage,
        headerRingRemarkStr:"Hz",
      });
    }else{
      this.setData({
        showHzorErr : false,
        vfdStatusStyel:"unpowered",
        headerStatutsStr:"停机",
        ringStatus:"",
        headerRingIconImage: this.data.unpoweredImage,
      });
    }
  },
  getData: function (params) {
    for(let key in params){
        switch(key){
          case "1":
            if(params[1].slice(2,4) == "03"){
              console.log("得到的03modbus码"+params[1]);
              this.getDataProcessingRead(params[1]);
            }else if(params[1].slice(2,4) == "06"){
              console.log("得到的06modbus码"+params[1]);
              this.getDataProcessingWrite(params[1]);
            }
            break;
        }
    }
  }
})

function toOneDecimal(params) {
  const lastIndex = params.lastIndexOf(".");
  if (lastIndex !== -1) {
    return params.slice(0, lastIndex + 2);
  } else {
    return params;
  }
  
}
function toLastAddDecimal(params) {
  const str = params;
  const modifiedStr  = str.length === 1 ? "0."+str : str.slice(0,-1) + "." + str.slice(-1);
  return modifiedStr;
}
function toTwoDecimalPlaces(params) {
  return parseFloat(params).toFixed(2);
}
